package afters

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/httplib"
	"smart_home/api/models"
	"smart_home/api/xfyun/depots"
	"time"
)

func init() {
	registerAfter("switch_default", switch_default)
}

// 开关
func switch_default(intent *depots.Intent, result *depots.Result) {
	var (
		uid  string
		sta  string
		name string
		act  bool
		ok   bool
	)

	if _, ok = intent.Data.Result[0].Data["uid"]; ok {
		uid = intent.Data.Result[0].Data["uid"].(string)
	}

	if _, ok = intent.Data.Result[0].Data["sta"]; ok {
		sta = intent.Data.Result[0].Data["sta"].(string)
	}

	if _, ok = intent.Data.Result[0].Data["name"]; ok {
		name = intent.Data.Result[0].Data["name"].(string)
	}

	if _, ok = intent.Data.Result[0].Data["act"]; ok {
		act = intent.Data.Result[0].Data["act"].(bool)
	}

	result.Answer.Text = switch_export(uid, sta, name, act, 500)
}

// 操作设备输出
// @param uid string true 用户id
// @param sta string true 操作设备sta
// @param equipmentName string true 操作设备名称
// @param act bool true 设备操作
// @param aftime int64 true 超时时间
func switch_export(uid, sta, equipmentName string, act bool, aftime int64) string {
	var (
		url    string = "http://api.rcenet.com/v2/switch/"
		err    error
		ch     chan string
		actMsg string
	)

	if act {
		url += "open/"
		actMsg = "打开"
	} else {
		url += "close/"
		actMsg = "关闭"
	}
	url += sta

	ch = make(chan string)
	// 2.8秒过期
	after := time.After(time.Duration(aftime) * time.Millisecond)

	go func(ch chan string, actMsg, equipmentName string) {
		resMsg := &models.ResultMsg{}
		if err = httplib.Get(url).Header("st", beego.AppConfig.String("st")).Header("suid", uid).ToJSON(resMsg); err != nil {
			ch <- err.Error()
			return
		}
		if resMsg.Code == 0 {
			ch <- resMsg.Msg
		} else {
			ch <- fmt.Sprintf("已为您%s%s", actMsg, equipmentName)
		}
	}(ch, actMsg, equipmentName)

	select {
	case d := <-ch:
		return d
	case <-after:
		return fmt.Sprintf("正在为您%s%s", actMsg, equipmentName)
	}
}
